﻿using StockHelper.Scripts;
using StockHelper.Scripts.Comm;
using StockHelper.Scripts.Stock;
using StockHelper.Scripts.Types;
using StockHelper.Style;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using Timer = StockHelper.Scripts.Comm.Timer;

namespace StockHelper
{
    public partial class TopMostBox : Form
    {
        private Point pos;
        private bool mouseDown = false;
        private List<Data> itemList = new List<Data>();
        private bool isPercentage = false;
        public static TopMostBox e;
        private Color textColor = Color.White;

        public TopMostBox()
        {
            e = this;
            InitializeComponent();


            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景. 
            SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲
        }

        private void TopMostBox_Load(object sender, EventArgs e)
        {
            this.TopMost = Config.Get("topMost/isTop", "1") == "1";
            isPercentage = Config.Get("topMost/isPercentage", "0").ToString() == "1";
            this.MouseDown += new MouseEventHandler(Event_MouseDown);
            this.MouseUp += new MouseEventHandler(Event_MouseUp);
            this.MouseMove += new MouseEventHandler(Event_MouseMove);
            this.MouseClick += new MouseEventHandler(Event_MouseClick);
            this.ItemList.MouseDown += new MouseEventHandler(Event_MouseDown);
            this.ItemList.MouseUp += new MouseEventHandler(Event_MouseUp);
            this.ItemList.MouseMove += new MouseEventHandler(Event_MouseMove);
            this.ItemList.MouseClick += new MouseEventHandler(Event_MouseClick);

            this.BackgroundImage = Assets.LoadImg(Config.Get("topMost/image", ""));

            string[] color = Config.Get("topMost/textColor", "255,255,255").Split(',');
            int[] _color = new int[3] { 255, 255, 255 };
            for (int i = 0; i < _color.Length; i++)
            {
                if (int.TryParse(color[i], out int o))
                    _color[i] = o;
            }
            textColor = Color.FromArgb(_color[0], _color[1], _color[2]);
            

            color = Config.Get("topMost/bgColor", "64,64,64").Split(',');
            _color = new int[3] { 64, 64, 64 };
            for (int i = 0; i < _color.Length; i++)
            {
                if (int.TryParse(color[i], out int o))
                    _color[i] = o;
            }
            
            if (this.BackgroundImage == null)
                this.BackColor = Color.FromArgb(_color[0], _color[1], _color[2]);
            else
                this.BackColor = Color.Transparent;

            if (Enum.TryParse(Config.Get("topMost/bgType", "Zoom"), out ImageLayout type))
                this.BackgroundImageLayout = type;

            CreatItems();
            StartPos();
            Timer.Add(Updata, 0, 3);
        }

        public void StartPos() {

            string pos = Config.Get("topMost/pos", "").ToString();
            Rectangle rect = Screen.GetWorkingArea(this);
            if (string.IsNullOrEmpty(pos))
            {
                this.Location = new Point((int)(rect.Width* 0.95f) - this.Width , (int)(rect.Height * 0.15f));
            }
            else
            {
                string[] vs = pos.Split(',');
                int x = int.Parse(vs[0]), y = int.Parse(vs[1]);
                if (x < 0 || x + this.Width > rect.Width)
                    x = (int)(rect.Width * 0.95f) - this.Width;
                if (y < 0 || y + this.Height > rect.Height)
                    y = (int)(rect.Height * 0.9f) - this.Height;
                this.Location = new Point(x, y);
            }

        }



        public void Updata()
        {
            foreach (Data data in itemList)
            {
                if (StockCtrl.GetData(data.key) == null)
                    continue;
                bool 是否涨价 = (bool)StockCtrl.GetData(data.key, Param.是否涨价);
                data.price.Text = StockCtrl.GetData(data.key, Param.当前价格).ToString();
                if (isPercentage)
                    data.price2.Text = StockCtrl.GetData(data.key, Param.涨跌百分比).ToString();
                else
                    data.price2.Text = StockCtrl.GetData(data.key, Param.涨跌值).ToString();
                data.price2.ForeColor = 是否涨价 ? Color.Red : Color.Lime;
            }
        }


        public void CreatItems()
        {
            this.ItemList.Controls.Clear();
            itemList.Clear();
            ArrayList passlist = Config.Get("topMost/passlist", new ArrayList()) as ArrayList;
            foreach (string key in Config.Get("stockList", new ArrayList()))
            {
                if (passlist.IndexOf(key) == -1)
                {
                    if (this.ItemList.Controls.Count > 0)
                        this.ItemList.Controls.Add(new PictureBox
                        {
                            Size = new Size(180, 1),
                            BackColor =  Color.LightGray,
                            Margin = new Padding(10, 3, 10, 3),
                        });
                    Panel panel = new Panel
                    {
                        Size = new Size(200, 30),
                        BackColor = Color.Transparent,
                        Margin = new Padding(0),
                        ForeColor = Color.Transparent,
                    };
                    ExLabel name = new ExLabel
                    {
                        Text = StockCtrl.GetData(key, Param.名称).ToString(),
                        TextAlign = ContentAlignment.MiddleLeft,
                        BackColor = Color.Transparent,
                        ForeColor = textColor,
                        Dock = DockStyle.Left,
                        Size = new Size(90, 25),
                        //AutoSize = true,
                        Font = new Font("微软雅黑",11),
                    };
                    ExLabel price = new ExLabel
                    {
                        Text = StockCtrl.GetData(key, Param.当前价格).ToString(),
                        TextAlign = ContentAlignment.MiddleCenter,
                        BackColor = Color.Transparent,
                        ForeColor = textColor,
                        Size = new Size(60, 25),
                        Location = new Point(90, 0),
                        //AutoSize = true,
                        Font = new Font("微软雅黑", 11),
                    };

                    bool 是否涨价 = (bool)StockCtrl.GetData(key, Param.是否涨价);
                    ExLabel price2 = new ExLabel
                    {
                        Text = isPercentage ? StockCtrl.GetData(key, Param.涨跌百分比).ToString() : StockCtrl.GetData(key, Param.涨跌值).ToString(),
                        //TextAlign = ContentAlignment.MiddleCenter,
                        TextAlign = ContentAlignment.MiddleLeft,
                        BackColor = Color.Transparent,
                        ForeColor = 是否涨价?  Color.Red : Color.Lime ,
                        Size = new Size(60, 25),
                        Location = new Point(150, 0),
                        //AutoSize = true,
                        Font = new Font("微软雅黑", 11),
                    };
                    itemList.Add(new Data {
                        key = key,
                        price = price,
                        price2 = price2,
                    });
                    panel.Controls.Add(name);
                    panel.Controls.Add(price);
                    panel.Controls.Add(price2);
                    BindEvent(name);
                    BindEvent(price);
                    BindEvent(price2);
                    this.ItemList.Controls.Add(panel);
                }
            }
            this.Height = this.ItemList.Height + 20;
        }
        


        private void BindEvent(ExLabel t)
        {
            t.MouseClick += new MouseEventHandler(Event_MouseClick);
            t.MouseDown += new MouseEventHandler(Event_MouseDown);
            t.MouseUp += new MouseEventHandler(Event_MouseUp);
            t.MouseMove += new MouseEventHandler(Event_MouseMove);
        }

        private void OpacityEvent(object sender, EventArgs e)
        {
            ToolStripMenuItem item = sender as ToolStripMenuItem;
            this.Opacity = float.Parse(item.Text.Substring(0, item.Text.Length - 1)) / 100f;
            Config.Set("topMost/opacity", this.Opacity);
        }


        private void Event_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                pos = new Point(this.Location.X - Control.MousePosition.X, this.Location.Y - Control.MousePosition.Y);
                mouseDown = true;
            }
        }

        private void Event_MouseMove(object sender, MouseEventArgs e)
        {
            if (mouseDown)
            {
                this.Location = new Point(pos.X + Control.MousePosition.X, pos.Y + Control.MousePosition.Y);
            }
        }

        private void Event_MouseUp(object sender, MouseEventArgs e)
        {
            mouseDown = false;
            Config.Set("topMost/pos", this.Location.X + "," + this.Location.Y);
        }

        private void Event_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                this.contextMenuStrip1.Show(this, new Point(e.X, e.Y));
                this.总在最前ToolStripMenuItem.Checked = this.TopMost;
            }
        }

        private void 鼠标穿透ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MousePenetration.SetWindowLong(this.Handle, MousePenetration.GWL_EXSTYLE, MousePenetration.WS_EX_TRANSPARENT | MousePenetration.WS_EX_LAYERED);
        }

        private void 关闭悬浮窗ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CloseForm();
        }

        private void TopMostBox_FormClosing(object sender, FormClosingEventArgs e)
        {
            Timer.Remove(Updata);
        }

        public void CloseForm() {
            Timer.Remove(Updata);
            Config.Set("topMost/show", "0");
            this.Close();
            this.Dispose();
        }
        
        public void SetWindowRegion()
        {
            System.Drawing.Drawing2D.GraphicsPath FormPath;
            FormPath = new System.Drawing.Drawing2D.GraphicsPath();
            Rectangle rect = new Rectangle(0, 0, this.Width, this.Height);
            FormPath = GetRoundedRectPath(rect, 15);
            this.Region = new Region(FormPath);
        }
        private GraphicsPath GetRoundedRectPath(Rectangle rect, int radius)
        {
            int diameter = radius;
            Rectangle arcRect = new Rectangle(rect.Location, new Size(diameter, diameter));
            GraphicsPath path = new GraphicsPath();
            // 左上角
            path.AddArc(arcRect, 180, 90);
            // 右上角
            arcRect.X = rect.Right - diameter;
            path.AddArc(arcRect, 270, 90);
            // 右下角
            arcRect.Y = rect.Bottom - diameter;
            path.AddArc(arcRect, 0, 90);
            // 左下角
            arcRect.X = rect.Left;
            path.AddArc(arcRect, 90, 90);
            path.CloseFigure();//闭合曲线
            return path;
        }
        

        private void TopMostBox_Paint(object sender, PaintEventArgs e)
        {
            if(Config.Get("topMost/region", "1") == "1")
                SetWindowRegion();
        }


        private class Data {
            public string key;
            public ExLabel price;
            public ExLabel price2;
        }

        private void 涨跌百分比ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.涨跌百分比ToolStripMenuItem.Checked = isPercentage = !isPercentage;
            Config.Set("topMost/isPercentage", isPercentage ? "1" : "0");
            Updata();
        }

        private void 总在最前ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.总在最前ToolStripMenuItem.Checked = this.TopMost = !this.TopMost;
             Config.Set("topMost/isTop", this.TopMost ? "1" : "0");
        }

        private void 设置背景图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string path = File.OpenFile("图片(*.*)|*.*");
            if (string.IsNullOrEmpty(path))
                return;
            try
            {
                string newPath = "topMostBg" + System.IO.Path.GetExtension(path);
                File.Copy(path, "Assets\\" + newPath);
                this.BackgroundImage = Assets.LoadImg(newPath);
                Config.Set("topMost/image", newPath);
            }
            catch {
                MessageBox.Show("图片异常");
            }
        }

        private void TopMostBox_SizeChanged(object sender, EventArgs e)
        {
            if (Config.Get("topMost/region", "1") == "1")
                SetWindowRegion();
        }
    }
}